// 智谱API配置
const ZHIPU_API_CONFIG = {
    baseURL: 'https://open.bigmodel.cn/api/paas/v4/chat/completions',
    apiKey: '', // 需要用户配置
    model: 'glm-4-flash'
};

// 本地存储键名
const STORAGE_KEYS = {
    API_KEY: 'zhipu_api_key',
    EDITOR_CONTENT: 'editor_content',
    DIARIES: 'diary_entries',
    CURRENT_DIARY_ID: 'current_diary_id',
    DIARY_STYLE: 'diary_style'
};

// 日记风格配置
const DIARY_STYLES = {
    emotional: {
        name: '感性风格',
        description: '温暖细腻，情感丰富',
        systemPrompt: '你是一个温暖细腻的日记伙伴，善于用感性的语言表达情感，关注内心感受和情感细节。'
    },
    chatty: {
        name: '话痨风格', 
        description: '活泼健谈，详细生动',
        systemPrompt: '你是一个活泼健谈的日记伙伴，喜欢详细描述，用生动有趣的语言记录生活，善于发现生活中的小细节。'
    },
    minimal: {
        name: '简约风格',
        description: '简洁明了，言简意赅',
        systemPrompt: '你是一个简约风格的日记伙伴，善于用简洁明了的语言表达核心思想，注重精炼和深度。'
    }
};

// 预置提示词（会根据日记风格动态调整）
const PROMPTS = {
    polish: (style) => {
        const basePrompt = `你是一个贴心的日记写作助手。请对用户提供的日记内容进行润色美化，要求：
1. 保持原意和真实情感不变
2. 让文字表达更加生动温暖
3. 适合个人日记的亲切风格
4. 保持内容的真实性和个人色彩
5. 直接返回润色后的内容，使用纯文本格式
6. 不要添加额外说明

`;
        return basePrompt + `风格要求：${DIARY_STYLES[style].description}\n\n用户内容：`;
    },

    expand: (style) => {
        const basePrompt = `你是一个富有想象力的日记写作伙伴。请对用户提供的日记片段进行灵感扩展，要求：
1. 保持原有情感基调和真实性
2. 丰富情感表达和细节描述
3. 添加合理的联想和感悟
4. 保持日记的个人化风格
5. 直接返回扩展后的内容，使用纯文本格式
6. 不要添加额外说明

`;
        return basePrompt + `风格要求：${DIARY_STYLES[style].description}\n\n用户内容：`;
    },

    summarize: (style) => {
        const basePrompt = `你是一个善于提炼的日记整理助手。请对用户提供的日记内容进行精华提炼，要求：
1. 提取核心情感和重要感悟
2. 保持个人化的表达风格
3. 突出最有意义的部分
4. 保持日记的温度和真实感
5. 直接返回提炼后的内容，使用纯文本格式
6. 不要添加额外说明

`;
        return basePrompt + `风格要求：${DIARY_STYLES[style].description}\n\n用户内容：`;
    }
};

// DOM元素
const elements = {
    // 编辑器相关
    contentEditor: document.getElementById('contentEditor'),
    diaryTitle: document.getElementById('diaryTitle'),
    saveDiaryBtn: document.getElementById('saveDiaryBtn'),
    clearBtn: document.getElementById('clearBtn'),
    copyBtn: document.getElementById('copyBtn'),
    
    // 日记风格选择器
    diaryStyleSelect: document.getElementById('diaryStyleSelect'),
    
    // 日记列表相关
    examplesSidebar: document.getElementById('examplesSidebar'),
    toggleExamples: document.getElementById('toggleExamples'),
    expandExamples: document.getElementById('expandExamples'),
    newDiaryBtn: document.getElementById('newDiaryBtn'),
    diaryList: document.getElementById('diaryList'),
    
    // 文件上传相关
    fileInput: document.getElementById('fileInput'),
    uploadBtn: document.getElementById('uploadBtn'),
    
    // API配置相关
    toggleConfig: document.getElementById('toggleConfig'),
    configPanel: document.getElementById('configPanel'),
    apiKeyInput: document.getElementById('apiKeyInput'),
    saveApiKey: document.getElementById('saveApiKey'),
    configStatus: document.getElementById('configStatus'),
    
    // AI功能相关
    polishBtn: document.getElementById('polishBtn'),
    expandBtn: document.getElementById('expandBtn'),
    summarizeBtn: document.getElementById('summarizeBtn'),
    resultContent: document.getElementById('resultContent'),
    copyResultBtn: document.getElementById('copyResultBtn'),
    
    // 加载状态
    loadingModal: document.getElementById('loadingModal'),
    
    // AI对话相关
    chatMessages: document.getElementById('chatMessages'),
    chatInput: document.getElementById('chatInput'),
    sendChatBtn: document.getElementById('sendChatBtn'),
    exportChatBtn: document.getElementById('exportChatBtn'),
    clearChatBtn: document.getElementById('clearChatBtn'),
    
    // AI功能区域隐藏/展开
    collapseAiSection: document.getElementById('collapseAiSection'),
    expandAiSection: document.getElementById('expandAiSection'),
    aiSection: document.querySelector('.ai-section'),
    chatSection: document.querySelector('.chat-section')
};

// 工具函数
// 日记管理类
class DiaryManager {
    static generateId() {
        return 'diary_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
    }

    static getCurrentStyle() {
        return Utils.getFromStorage(STORAGE_KEYS.DIARY_STYLE) || 'emotional';
    }

    static setCurrentStyle(style) {
        Utils.saveToStorage(STORAGE_KEYS.DIARY_STYLE, style);
    }

    static getAllDiaries() {
        const diaries = Utils.getFromStorage(STORAGE_KEYS.DIARIES);
        return diaries ? JSON.parse(diaries) : [];
    }

    static saveDiary(id, title, content) {
        const diaries = this.getAllDiaries();
        const existingIndex = diaries.findIndex(d => d.id === id);
        
        const diaryEntry = {
            id: id || this.generateId(),
            title: title || '无标题日记',
            content: content,
            createdAt: existingIndex >= 0 ? diaries[existingIndex].createdAt : new Date().toISOString(),
            updatedAt: new Date().toISOString(),
            style: this.getCurrentStyle()
        };

        if (existingIndex >= 0) {
            diaries[existingIndex] = diaryEntry;
        } else {
            diaries.unshift(diaryEntry);
        }

        Utils.saveToStorage(STORAGE_KEYS.DIARIES, JSON.stringify(diaries));
        return diaryEntry;
    }

    static deleteDiary(id) {
        const diaries = this.getAllDiaries();
        const filteredDiaries = diaries.filter(d => d.id !== id);
        Utils.saveToStorage(STORAGE_KEYS.DIARIES, JSON.stringify(filteredDiaries));
    }

    static getDiary(id) {
        const diaries = this.getAllDiaries();
        return diaries.find(d => d.id === id);
    }

    static getCurrentDiaryId() {
        return Utils.getFromStorage(STORAGE_KEYS.CURRENT_DIARY_ID);
    }

    static setCurrentDiaryId(id) {
        Utils.saveToStorage(STORAGE_KEYS.CURRENT_DIARY_ID, id);
    }

    static renderDiaryList() {
        const diaries = this.getAllDiaries();
        const diaryList = elements.diaryList;
        
        if (diaries.length === 0) {
            diaryList.innerHTML = `
                <div class="no-diaries">
                    <p>📝 还没有日记</p>
                    <p>点击"新建"开始记录生活</p>
                </div>
            `;
            return;
        }

        diaryList.innerHTML = diaries.map(diary => {
            const date = new Date(diary.createdAt).toLocaleDateString('zh-CN');
            const preview = diary.content.substring(0, 50) + (diary.content.length > 50 ? '...' : '');
            const isActive = diary.id === this.getCurrentDiaryId() ? 'active' : '';
            
            return `
                <div class="diary-item ${isActive}" data-id="${diary.id}">
                    <div class="diary-header">
                        <h4>${diary.title}</h4>
                        <span class="diary-date">${date}</span>
                        <button class="delete-diary-btn" data-id="${diary.id}">×</button>
                    </div>
                    <div class="diary-preview">${preview}</div>
                </div>
            `;
        }).join('');

        // 绑定点击事件
        diaryList.querySelectorAll('.diary-item').forEach(item => {
            item.addEventListener('click', (e) => {
                if (!e.target.classList.contains('delete-diary-btn')) {
                    this.loadDiary(item.dataset.id);
                }
            });
        });

        // 绑定删除事件
        diaryList.querySelectorAll('.delete-diary-btn').forEach(btn => {
            btn.addEventListener('click', (e) => {
                e.stopPropagation();
                if (confirm('确定要删除这篇日记吗？')) {
                    this.deleteDiary(btn.dataset.id);
                    this.renderDiaryList();
                    if (btn.dataset.id === this.getCurrentDiaryId()) {
                        this.newDiary();
                    }
                }
            });
        });
    }

    static loadDiary(id) {
        const diary = this.getDiary(id);
        if (diary) {
            elements.diaryTitle.value = diary.title;
            elements.contentEditor.value = diary.content;
            this.setCurrentDiaryId(id);
            this.renderDiaryList(); // 更新活跃状态
        }
    }

    static newDiary() {
        elements.diaryTitle.value = '';
        elements.contentEditor.value = '';
        this.setCurrentDiaryId('');
        this.renderDiaryList();
    }

    static saveCurrentDiary() {
        const title = elements.diaryTitle.value.trim();
        const content = elements.contentEditor.value.trim();
        
        if (!content) {
            Utils.showToast('请输入日记内容');
            return;
        }

        const currentId = this.getCurrentDiaryId();
        const savedDiary = this.saveDiary(currentId, title, content);
        this.setCurrentDiaryId(savedDiary.id);
        this.renderDiaryList();
        Utils.showToast('日记保存成功');
    }
}

// 文件处理类
class FileProcessor {
    static async processTextFile(file) {
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.onload = (e) => {
                resolve(e.target.result);
            };
            reader.onerror = () => {
                reject(new Error('文件读取失败'));
            };
            reader.readAsText(file, 'UTF-8');
        });
    }

    static async convertToPrompt(content) {
        const currentStyle = DiaryManager.getCurrentStyle();
        const stylePrompt = DIARY_STYLES[currentStyle].systemPrompt;
        
        const prompt = `${stylePrompt}

请将以下文本内容总结并转换为适合写入日记的语句，保持原文的核心信息和情感色彩：

${content}`;
        
        try {
            Utils.showLoading();
            const result = await AIService.callAPI(prompt, '');
            Utils.hideLoading();
            return result;
        } catch (error) {
            Utils.hideLoading();
            throw error;
        }
    }

    static async handleFileUpload() {
        const file = elements.fileInput.files[0];
        if (!file) {
            Utils.showToast('请选择一个txt文件');
            return;
        }

        if (!file.name.toLowerCase().endsWith('.txt')) {
            Utils.showToast('只支持txt格式的文件');
            return;
        }

        if (file.size > 1024 * 1024) { // 1MB限制
            Utils.showToast('文件大小不能超过1MB');
            return;
        }

        try {
            const content = await this.processTextFile(file);
            const processedContent = await this.convertToPrompt(content);
            
            // 将处理后的内容添加到编辑器
            const currentContent = elements.contentEditor.value;
            const newContent = currentContent ? currentContent + '\n\n' + processedContent : processedContent;
            elements.contentEditor.value = newContent;
            
            Utils.showToast('文件处理完成，内容已添加到编辑器');
            elements.fileInput.value = ''; // 清空文件选择
        } catch (error) {
            console.error('文件处理失败:', error);
            Utils.showError('文件处理失败: ' + error.message);
        }
    }
}

class Utils {
    // 获取选中的文本
    static getSelectedText() {
        const editor = elements.contentEditor;
        const start = editor.selectionStart;
        const end = editor.selectionEnd;
        
        if (start === end) {
            // 如果没有选中文本，返回全部内容
            return editor.value.trim();
        }
        
        return editor.value.substring(start, end).trim();
    }

    // 显示加载状态
    static showLoading() {
        elements.loadingModal.style.display = 'flex';
        // 禁用所有AI按钮
        elements.polishBtn.disabled = true;
        elements.expandBtn.disabled = true;
        elements.summarizeBtn.disabled = true;
    }

    // 隐藏加载状态
    static hideLoading() {
        elements.loadingModal.style.display = 'none';
        // 启用所有AI按钮
        elements.polishBtn.disabled = false;
        elements.expandBtn.disabled = false;
        elements.summarizeBtn.disabled = false;
    }

    // 显示结果
    static showResult(content) {
        elements.resultContent.innerHTML = `
            <div class="ai-response">${content}</div>
        `;
        elements.copyResultBtn.style.display = 'block';
    }

    // 显示错误信息
    static showError(message) {
        elements.resultContent.innerHTML = `
            <div class="error-message" style="color: #ef4444; padding: 16px; background: #fef2f2; border: 1px solid #fecaca; border-radius: 8px;">
                <strong>处理失败：</strong>${message}
            </div>
        `;
        elements.copyResultBtn.style.display = 'none';
    }

    // 复制文本到剪贴板
    static async copyToClipboard(text) {
        try {
            await navigator.clipboard.writeText(text);
            this.showToast('已复制到剪贴板');
        } catch (err) {
            // 降级方案
            const textArea = document.createElement('textarea');
            textArea.value = text;
            document.body.appendChild(textArea);
            textArea.select();
            document.execCommand('copy');
            document.body.removeChild(textArea);
            this.showToast('已复制到剪贴板');
        }
    }

    // 显示提示消息
    static showToast(message) {
        const toast = document.createElement('div');
        toast.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            background: #10b981;
            color: white;
            padding: 12px 20px;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
            z-index: 1001;
            font-size: 14px;
            animation: slideIn 0.3s ease;
        `;
        toast.textContent = message;
        
        // 添加动画样式
        const style = document.createElement('style');
        style.textContent = `
            @keyframes slideIn {
                from { transform: translateX(100%); opacity: 0; }
                to { transform: translateX(0); opacity: 1; }
            }
        `;
        document.head.appendChild(style);
        
        document.body.appendChild(toast);
        
        setTimeout(() => {
            toast.remove();
            style.remove();
        }, 3000);
    }
    
    // 本地存储相关
    static saveToStorage(key, value) {
        try {
            localStorage.setItem(key, value);
            return true;
        } catch (err) {
            console.error('保存到本地存储失败:', err);
            return false;
        }
    }
    
    static getFromStorage(key) {
        try {
            return localStorage.getItem(key);
        } catch (err) {
            console.error('从本地存储读取失败:', err);
            return null;
        }
    }
    
    // 检查API密钥是否已配置
    static isApiKeyConfigured() {
        const apiKey = this.getFromStorage(STORAGE_KEYS.API_KEY);
        return apiKey && apiKey.trim().length > 0;
    }
    
    // 更新配置状态显示
    static updateConfigStatus() {
        const statusElement = elements.configStatus;
        if (this.isApiKeyConfigured()) {
            statusElement.innerHTML = '<span class="configured">已配置</span>';
        } else {
            statusElement.innerHTML = '<span>未配置</span>';
        }
    }
}

// AI API调用类
class AIService {
    static async callAPI(prompt, content) {
        // 检查API密钥
        const apiKey = Utils.getFromStorage(STORAGE_KEYS.API_KEY);
        if (!apiKey || apiKey.trim().length === 0) {
            throw new Error('请先配置API密钥');
        }

        try {
            const response = await fetch(ZHIPU_API_CONFIG.baseURL, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${apiKey}`
                },
                body: JSON.stringify({
                    model: ZHIPU_API_CONFIG.model,
                    messages: [
                        {
                            role: 'user',
                            content: `${prompt}\n\n需要处理的内容：\n${content}`
                        }
                    ],
                    temperature: 0.7,
                    max_tokens: 2000
                })
            });

            if (!response.ok) {
                if (response.status === 401) {
                    throw new Error('API密钥无效，请检查配置');
                }
                throw new Error(`API请求失败: ${response.status}`);
            }

            const data = await response.json();
            return data.choices[0].message.content;
        } catch (error) {
            console.error('API调用错误:', error);
            if (error.message.includes('API密钥')) {
                throw error;
            }
            throw new Error('AI服务暂时不可用，请稍后重试');
        }
    }

    static async processContent(type, content) {
        if (!content) {
            throw new Error('请先选择要处理的内容');
        }

        const prompt = PROMPTS[type];
        if (!prompt) {
            throw new Error('未知的处理类型');
        }

        return await this.callAPI(prompt, content);
    }
}

// 事件处理类
class EventHandlers {
    static bindEvents() {
        // 日记列表展开收起
        elements.toggleExamples.addEventListener('click', EventHandlers.handleToggleExamples);
        elements.expandExamples.addEventListener('click', EventHandlers.handleExpandExamples);
        
        // 日记相关事件
        elements.saveDiaryBtn.addEventListener('click', EventHandlers.handleSaveDiary);
        elements.newDiaryBtn.addEventListener('click', EventHandlers.handleNewDiary);
        elements.uploadBtn.addEventListener('click', EventHandlers.handleUploadClick);
        elements.fileInput.addEventListener('change', EventHandlers.handleFileChange);
        elements.diaryStyleSelect.addEventListener('change', EventHandlers.handleStyleChange);
        
        // API配置相关
        elements.toggleConfig.addEventListener('click', EventHandlers.handleToggleConfig);
        elements.saveApiKey.addEventListener('click', EventHandlers.handleSaveApiKey);
        elements.apiKeyInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                EventHandlers.handleSaveApiKey();
            }
        });
        
        // AI功能按钮事件
        elements.polishBtn.addEventListener('click', () => EventHandlers.handleAIFunction('polish'));
        elements.expandBtn.addEventListener('click', () => EventHandlers.handleAIFunction('expand'));
        elements.summarizeBtn.addEventListener('click', () => EventHandlers.handleAIFunction('summarize'));
        
        // 复制按钮事件
        elements.copyResultBtn.addEventListener('click', EventHandlers.handleCopyResult);
        elements.copyBtn.addEventListener('click', EventHandlers.handleCopyAll);
        
        // 清空按钮事件
        elements.clearBtn.addEventListener('click', EventHandlers.handleClearEditor);
        
        // 编辑器内容自动保存
        elements.contentEditor.addEventListener('input', EventHandlers.handleContentChange);
        
        // AI对话事件
        elements.sendChatBtn.addEventListener('click', EventHandlers.handleSendChat);
        elements.chatInput.addEventListener('keydown', EventHandlers.handleChatKeydown);
        elements.exportChatBtn.addEventListener('click', EventHandlers.handleExportChat);
        elements.clearChatBtn.addEventListener('click', EventHandlers.handleClearChat);
        
        // AI功能区域隐藏/展开事件
        elements.collapseAiSection.addEventListener('click', EventHandlers.handleCollapseAiSection);
        elements.expandAiSection.addEventListener('click', EventHandlers.handleExpandAiSection);
    }
    
    static handleToggleExamples() {
        const sidebar = elements.examplesSidebar;
        const toggleBtn = elements.toggleExamples;
        const expandBtn = elements.expandExamples;
        
        if (sidebar.classList.contains('collapsed')) {
            sidebar.classList.remove('collapsed');
            toggleBtn.textContent = '收起';
            expandBtn.style.display = 'none';
        } else {
            sidebar.classList.add('collapsed');
            toggleBtn.textContent = '展开';
            expandBtn.style.display = 'flex';
        }
    }
    
    static handleExpandExamples() {
        const sidebar = elements.examplesSidebar;
        const toggleBtn = elements.toggleExamples;
        const expandBtn = elements.expandExamples;
        
        sidebar.classList.remove('collapsed');
        toggleBtn.textContent = '收起';
        expandBtn.style.display = 'none';
    }
    
    static handleToggleConfig() {
        const panel = elements.configPanel;
        const button = elements.toggleConfig;
        
        if (panel.style.display === 'none') {
            panel.style.display = 'block';
            button.textContent = '收起';
        } else {
            panel.style.display = 'none';
            button.textContent = '设置';
        }
    }
    
    static handleSaveApiKey() {
        const apiKey = elements.apiKeyInput.value.trim();
        if (!apiKey) {
            Utils.showToast('请输入API密钥');
            return;
        }
        
        if (Utils.saveToStorage(STORAGE_KEYS.API_KEY, apiKey)) {
            Utils.showToast('API密钥已保存');
            Utils.updateConfigStatus();
            elements.configPanel.style.display = 'none';
            elements.toggleConfig.textContent = '设置';
        } else {
            Utils.showToast('保存失败，请重试');
        }
    }
    
    static handleContentChange() {
        const content = elements.contentEditor.value;
        Utils.saveToStorage(STORAGE_KEYS.EDITOR_CONTENT, content);
    }

    // 日记相关事件处理
    static handleSaveDiary() {
        const title = elements.diaryTitle.value.trim();
        const content = elements.contentEditor.value.trim();
        
        if (!title) {
            Utils.showToast('请输入日记标题');
            elements.diaryTitle.focus();
            return;
        }
        
        if (!content) {
            Utils.showToast('请输入日记内容');
            elements.contentEditor.focus();
            return;
        }
        
        try {
            DiaryManager.saveDiary(title, content);
            Utils.showToast('日记保存成功');
        } catch (error) {
            console.error('保存日记失败:', error);
            Utils.showError('保存失败: ' + error.message);
        }
    }
    
    static handleNewDiary() {
        if (elements.contentEditor.value.trim() || elements.diaryTitle.value.trim()) {
            if (!confirm('当前有未保存的内容，确定要新建日记吗？')) {
                return;
            }
        }
        
        DiaryManager.createNewDiary();
        Utils.showToast('已创建新日记');
    }
    
    static handleUploadClick() {
        elements.fileInput.click();
    }
    
    static handleFileChange() {
        FileProcessor.handleFileUpload();
    }
    
    static handleStyleChange() {
        const selectedStyle = elements.diaryStyleSelect.value;
        DiaryManager.setCurrentStyle(selectedStyle);
        Utils.showToast(`已切换到${DIARY_STYLES[selectedStyle].name}风格`);
    }
    
    static handleDiaryClick(diaryId) {
        if (elements.contentEditor.value.trim() || elements.diaryTitle.value.trim()) {
            if (!confirm('当前有未保存的内容，确定要切换日记吗？')) {
                return;
            }
        }
        
        DiaryManager.loadDiary(diaryId);
    }
    
    static handleDeleteDiary(diaryId, event) {
        event.stopPropagation();
        
        if (!confirm('确定要删除这篇日记吗？此操作不可恢复。')) {
            return;
        }
        
        try {
            DiaryManager.deleteDiary(diaryId);
            Utils.showToast('日记已删除');
        } catch (error) {
            console.error('删除日记失败:', error);
            Utils.showError('删除失败: ' + error.message);
        }
    }

    static async handleAIFunction(type) {
        try {
            const selectedText = Utils.getSelectedText();
            
            if (!selectedText) {
                Utils.showError('请先输入内容或选择要处理的文本');
                return;
            }

            Utils.showLoading();
            
            const currentStyle = DiaryManager.getCurrentStyle();
            const prompt = PROMPTS[type](currentStyle);
            const result = await AIService.callAPI(prompt, selectedText);
            
            Utils.showResult(result);
            
        } catch (error) {
            console.error('AI处理错误:', error);
            Utils.showError(error.message);
        } finally {
            Utils.hideLoading();
        }
    }

    static handleCopyResult() {
        const resultElement = elements.resultContent.querySelector('.ai-response');
        if (resultElement) {
            Utils.copyToClipboard(resultElement.textContent);
        }
    }

    static handleClearEditor() {
        if (elements.contentEditor.value.trim() && confirm('确定要清空编辑器内容吗？')) {
            elements.contentEditor.value = '';
            Utils.saveToStorage(STORAGE_KEYS.EDITOR_CONTENT, '');
            elements.resultContent.innerHTML = `
                <div class="placeholder">
                    <p>选择编辑器中的文本，然后点击上方AI功能按钮</p>
                    <p>AI将为你提供专业的内容建议</p>
                </div>
            `;
            elements.copyResultBtn.style.display = 'none';
            elements.contentEditor.focus();
        }
    }

    static handleCopyAll() {
        if (elements.contentEditor.value.trim()) {
            Utils.copyToClipboard(elements.contentEditor.value);
        } else {
            Utils.showToast('编辑器内容为空');
        }
    }
    
    // AI对话相关事件处理
    static async handleSendChat() {
        const input = elements.chatInput;
        const message = input.value.trim();
        
        if (!message) {
            Utils.showToast('请输入消息');
            return;
        }
        
        // 添加用户消息到聊天记录
        EventHandlers.addChatMessage('user', message);
        input.value = '';
        
        try {
            // 显示AI正在思考
            const thinkingId = EventHandlers.addChatMessage('assistant', '正在思考...');
            
            // 获取当前日记风格
            const currentStyle = DiaryManager.getCurrentStyle();
            const stylePrompt = DIARY_STYLES[currentStyle].systemPrompt;
            
            // 构建带风格的系统提示
            const systemPrompt = `${stylePrompt}

你是用户的日记写作助手，请用${DIARY_STYLES[currentStyle].name}的风格与用户对话，帮助用户获得写作灵感和情感表达建议。`;
            
            // 调用AI API
            const response = await AIService.callAPI(systemPrompt, message);
            
            // 移除思考消息，添加AI回复
            EventHandlers.removeChatMessage(thinkingId);
            EventHandlers.addChatMessage('assistant', response);
            
        } catch (error) {
            console.error('AI对话错误:', error);
            EventHandlers.removeChatMessage(thinkingId);
            EventHandlers.addChatMessage('assistant', `抱歉，AI服务暂时不可用：${error.message}`);
        }
    }
    
    static handleChatKeydown(e) {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            EventHandlers.handleSendChat();
        }
    }
    
    static handleExportChat() {
        const messages = elements.chatMessages.querySelectorAll('.chat-message');
        if (messages.length === 0) {
            Utils.showToast('暂无对话记录');
            return;
        }
        
        let exportText = 'PPT助手对话记录\n\n';
        messages.forEach(msg => {
            const role = msg.classList.contains('user-message') ? '用户' : 'AI助手';
            const content = msg.querySelector('.message-content').textContent;
            exportText += `${role}：${content}\n\n`;
        });
        
        Utils.copyToClipboard(exportText);
        Utils.showToast('对话记录已复制到剪贴板');
    }
    
    static handleClearChat() {
        if (elements.chatMessages.children.length === 0) {
            Utils.showToast('对话记录已为空');
            return;
        }
        
        if (confirm('确定要清空所有对话记录吗？')) {
            elements.chatMessages.innerHTML = '';
            Utils.showToast('对话记录已清空');
        }
    }
    
    // AI功能区域隐藏/展开事件处理
    static handleCollapseAiSection() {
        elements.aiSection.style.display = 'none';
        elements.chatSection.style.display = 'none';
        elements.collapseAiSection.style.display = 'none';
        elements.expandAiSection.style.display = 'block';
    }
    
    static handleExpandAiSection() {
        elements.aiSection.style.display = 'block';
        elements.chatSection.style.display = 'block';
        elements.collapseAiSection.style.display = 'block';
        elements.expandAiSection.style.display = 'none';
    }
    
    // 聊天消息管理
    static addChatMessage(role, content) {
        const messageId = 'msg_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
        const messageDiv = document.createElement('div');
        messageDiv.className = `chat-message ${role}-message`;
        messageDiv.id = messageId;
        
        messageDiv.innerHTML = `
            <div class="message-content">${content}</div>
            <div class="message-time">${new Date().toLocaleTimeString()}</div>
        `;
        
        elements.chatMessages.appendChild(messageDiv);
        elements.chatMessages.scrollTop = elements.chatMessages.scrollHeight;
        
        return messageId;
    }
    
    static removeChatMessage(messageId) {
        const message = document.getElementById(messageId);
        if (message) {
            message.remove();
        }
    }
}

// 应用初始化类
class App {
    static init() {
        this.bindEvents();
        this.loadSavedContent();
        this.updateConfigStatus();
    }

    static bindEvents() {
        EventHandlers.bindEvents();
        
        // 键盘快捷键
        document.addEventListener('keydown', App.handleKeyboard);
    }

    static handleKeyboard(e) {
        // Ctrl+S 保存
        if (e.ctrlKey && e.key === 's') {
            e.preventDefault();
            Utils.showToast('内容已自动保存');
        }
        
        // Ctrl+A 全选编辑器内容
        if (e.ctrlKey && e.key === 'a' && document.activeElement === elements.contentEditor) {
            e.preventDefault();
            elements.contentEditor.select();
        }
    }

    static loadSavedContent() {
        // 加载保存的内容
        const savedContent = Utils.getFromStorage(STORAGE_KEYS.EDITOR_CONTENT);
        if (savedContent) {
            elements.contentEditor.value = savedContent;
        }
        
        // 加载保存的API密钥
        const savedApiKey = Utils.getFromStorage(STORAGE_KEYS.API_KEY);
        if (savedApiKey) {
            elements.apiKeyInput.value = savedApiKey;
        }
        
        // 加载日记风格设置
        const savedStyle = Utils.getFromStorage(STORAGE_KEYS.DIARY_STYLE);
        if (savedStyle && DIARY_STYLES[savedStyle]) {
            elements.diaryStyleSelect.value = savedStyle;
        }
    }
    
    static updateConfigStatus() {
        Utils.updateConfigStatus();
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    App.init();
    
    // 给编辑器焦点
    elements.contentEditor.focus();
    
    console.log('智能日记助手已加载完成');
    console.log('请配置智谱API密钥以使用AI功能');
});